package com.firefighting.maintenancer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.aspectj.weaver.ast.And;

import com.firefighting.util.JdbcUtils;
import com.firefighting.util.MYJSONObject;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.lang.StringBuffer;

/**
 * Servlet implementation class SubmitTaskItem
 */
@WebServlet(asyncSupported = true, urlPatterns = { "/SubmitTaskItem" })
public class SubmitTaskItem extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		System.out.println("-----"+format.format(new Date())+"    "+this.getServletName()+"-----");
		
		/*String maintenance_test_content_id=request.getParameter("maintenance_test_content_id");
		String task_id = request.getParameter("task_id");
		String maintenanceplan_id = request.getParameter("maintenanceplan_id");
		String taskItem_photo = request.getParameter("taskItem_photo");
		String json = request.getParameter("task_item_json");
		System.out.println("json="+json);*/
		
		String maintenance_test_content_id=null;
		String task_id =null;
		String maintenanceplan_id =null;
		String json =null;
				
		//String savePath = this.getServletContext().getRealPath("/cache_files");
		String savePath = "http://47.106.213.57:8080/image/taskitem";
		String saveFile = null;
		//Integer photoitem = 1;
		File test_file = new File(savePath);
		if (!test_file.exists()) {
			test_file.mkdirs();
		}
		System.out.println("savePath="+savePath);

		PrintWriter out = response.getWriter();
		MYJSONObject result_jb = new MYJSONObject();
		Connection connection = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String image_url = "";
		StringBuffer   stringBuffer=new StringBuffer();
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);//上传本地文件到服务器
			upload.setHeaderEncoding("UTF-8");
			if (!ServletFileUpload.isMultipartContent(request)) {
				result_jb.put("status", "false");
				result_jb.put("message", "普通表单");
				System.out.println("普通表单");
				return;
			 }
			List<FileItem> list = upload.parseRequest(request);//解析请求正文内容

			for (FileItem item : list) {
				if (item.isFormField()) {//判断是否是普通字段
					System.out.println("非文件数据项");
					String field_name = item.getFieldName(); //获取普通字段的字段名
                    //解决普通输入项的数据的中文乱码问题
                    String value = item.getString("UTF-8");//获取普通字段的值

            		System.out.println("---------表单传参----------");
            		System.out.println("field_name="+field_name);
            		System.out.println("value="+value);
            		System.out.println("---------表单传参结束------");
                    switch (field_name) {
						case "maintenance_test_content_id":
							maintenance_test_content_id = value;
							break;
						case "task_id":
							task_id = value;
							break;
						case "maintenanceplan_id":
							maintenanceplan_id = value;
							break;
						case "task_item_json":
							json = value;
							JSONObject task_item_json = JSONObject.fromObject(json);
							//System.out.println(jsonObject);
							JSONArray detail_content=task_item_json.getJSONArray("detail_content");
							//System.out.println(jsonArray1.toString());
						  for(int i=0;i< detail_content.size();i++)
						  {
							JSONObject item_object=  detail_content.getJSONObject(i);
							JSONArray item_jsonarray=item_object.getJSONArray("item_"+(i+1));
							//System.out.println(jsonArray2.toString());
							for(int j=0;j<item_jsonarray.size();j++)
							{
								JSONObject jsonObject3=item_jsonarray.getJSONObject(j);
								String name=jsonObject3.getString("name");
								String value_json=jsonObject3.getString("value");
								/*System.out.println(name);
								System.out.println(value);*/
								//stringBuffer.append(name+":"+value+",");
								if("语音".equals(name)||"照片".equals(name)||"视频".equals(name))
								{
									continue;
								}else 
								{
									stringBuffer.append(name+":"+value_json+"\n");
								}
								
							}
						  }
						 // System.out.println("stringBuffer="+stringBuffer);
							break;
						default:
							break;
					}
				} else {
					System.out.println("item.getSize="+item.getSize());
					if (item.getSize() > (1024 * 1024 * 100)) {
						result_jb.put("status", "false");
						result_jb.put("message", "上传文件超过100M");
						System.out.println("上传文件超过100M");
						return;
					}
					String filename = item.getName();//获取上传文件名
					System.out.println("filename="+filename);
					if (filename == null || "".equals(filename.trim())) {
						result_jb.put("status", "false");
						result_jb.put("message", "上传文件的文件名为空");
						System.out.println("上传文件的文件名为空");
						return;
					}
					//fileExtName为扩展名
					String fileExtName = filename.substring(filename.lastIndexOf(".") + 1);
					System.out.println("fileExtName="+fileExtName);
					if (!"jpg".equals(fileExtName)
							&& !"JPG".equals(fileExtName)
							&& !"jpeg".equals(fileExtName)
							&& !"JPEG".equals(fileExtName)
							&& !"png".equals(fileExtName)
							&& !"PNG".equals(fileExtName)) {

						result_jb.put("status", "false");
						result_jb.put("message", "上传文件格式不正确");
						System.out.println("上传文件格式不正确");
						return;
					}
					InputStream in = item.getInputStream();//以流的形式返回上传文件的主体内容
					format = new SimpleDateFormat("yyyyMMddHHmmss");
					String time = format.format(new Date());
					String current_time = String.valueOf(System.currentTimeMillis());
					String rand = current_time.substring(current_time.length()-2, current_time.length());
					String saveFilename = "TaskItem_" + task_id+"_"+time + rand + "." + fileExtName;
					System.out.println("saveFilename="+saveFilename);
					saveFile = savePath + "/" + saveFilename;
					System.out.println("saveFile="+saveFile);
					FileOutputStream outputStream = new FileOutputStream(saveFile);
					byte buffer[] = new byte[1024];
					int len = 0;
					while ((len = in.read(buffer)) > 0) {
						outputStream.write(buffer, 0, len);
					}
					in.close();
					outputStream.close();

					System.out.println("文件上传成功");
					/*image_url += request.getScheme() + "://" + request.getServerName() + ":" +request.getServerPort()+ request.getContextPath() 
						+ "/cache_files/"+saveFilename +";";*/
					image_url += savePath+"/"+saveFilename +";";
					System.out.println("image_url="+image_url);

				}
			}

			System.out.println("maintenance_test_content_id="+maintenance_test_content_id);
			System.out.println("task_id="+task_id);
			System.out.println("json="+json);
		
			if (!"".equals(image_url))
				image_url = image_url.substring(0, image_url.length()-1);
			System.out.println("image_url="+image_url);
		   //String execute_time=format.format(new Date());
			connection = JdbcUtils.getConnection();
			/*String sql="select  *  from task_item where task_item.task_id=? and task_item.maintenance_detail_id=?";
			ps = connection.prepareStatement(sql);
			ps.setString(1, task_id);
			ps.setString(2, maintenance_test_content_id);
			rs=ps.executeQuery();
			if(rs.next()) {*/
				
				//ps.close();
			String	sql ="update task_item set test_detail=?,test_detail_string=?,attachtable_photo=?,commit_time=?  "
						+ " where task_item.maintenance_detail_id=? and task_item.task_id=? ";
			/*}else {
				ps.close();
				sql ="insert into  task_item(test_detail,test_detail_string,attachtable_photo,maintenance_detail_id,task_id) values(?,?,?,?,?,?) ";
			}*/
			ps = connection.prepareStatement(sql);
			ps.setString(1, json);
			ps.setString(2, stringBuffer.toString());
			ps.setString(3, image_url);
			//ps.setDate(4, new java.sql.Date( (new Date()).getTime()));
			ps.setTimestamp(4, new java.sql.Timestamp(new Date().getTime()));
			ps.setString(5, maintenance_test_content_id);
			ps.setString(6, task_id);
		//	System.out.print(ps.executeUpdate()+"1111");
			String task_item_id=null;
			ResultSet rs1;
			String maintenance_test_content_serial=null;
			if (ps.executeUpdate() > 0) {
				ps.close();
				sql ="update maintenanceplan_content set maintenanceplan_content.state_finished=? from maintenanceplan_content ,task "
						+ " where maintenanceplan_content.maintenanceplan_id=? and maintenanceplan_content.maintenance_content_id=? "
						+ "and task.id=? and task.building_id=maintenanceplan_content.building_id and "
						+ "task.maintenanceplan_id=maintenanceplan_content.maintenanceplan_id";
				ps = connection.prepareStatement(sql);
				ps.setString(1, "已执行");
				ps.setString(2, maintenanceplan_id);
				ps.setString(3, maintenance_test_content_id);
				ps.setString(4, task_id);
			//	System.out.print(ps.executeUpdate()+"mmmmmmmmmmm");
				if(ps.executeUpdate() > 0)
				{
					
					ps.close();
				    sql ="select task_item.id from task_item where task_item.task_id=? and task_item.maintenance_detail_id=?";
				    ps = connection.prepareStatement(sql);
				    ps.setString(1, task_id);
				    ps.setString(2, maintenance_test_content_id);
				    rs=ps.executeQuery();
		     	   if(rs.next())
			        {
		            task_item_id=rs.getString(1);
		            result_jb.put("status", "true");
				    result_jb.put("task_item_id", task_item_id);
				   //result_jb.put("message", "提交数据成功");
				   ps.close();
				   sql ="select maintenance_test_content.serial from maintenance_test_content where maintenance_test_content.id=?";
				   ps = connection.prepareStatement(sql);
				   ps.setString(1, maintenance_test_content_id);
				   rs1=ps.executeQuery();
				   if(rs1.next())
			       {
				   maintenance_test_content_serial=rs1.getString(1);
				   result_jb.put("maintenance_test_content_state_finished", "已执行");
		          result_jb.put("maintenance_test_content_serial", maintenance_test_content_serial);
		          result_jb.put("message", "提交数据成功");
			      }else {
			    	result_jb.put("status", "false");
					result_jb.put("message", "提交数据出错");
					System.out.print("返回三级维保项目序列号失败");
			    }
				}else 
			    {
				result_jb.put("status", "false");
				result_jb.put("message", "提交数据出错");
				System.out.print("没找到最大id数据");
			    }
			}else{
				result_jb.put("status", "false");
				result_jb.put("message", "未更新1");
			}
			}else {
				result_jb.put("status", "false");
				result_jb.put("message", "未更新2");
			}
			
	     	
	}
		catch (SQLException e) {
			e.printStackTrace();
			result_jb.put("status", "false");
			result_jb.put("message", "服务器异常");
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			JdbcUtils.free(rs, ps, connection);
			out.print(result_jb.toString());
			System.out.println("hhhhhhhhhhhhhhhhhhhhhhhh");
			System.out.println(result_jb.toString());
			out.flush();
			out.close();
		}
	}

}
